/*
 * Copyright (c) 2016. André Mion
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.sample.andremion.musicplayer.activities;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.CheckResult;
import android.support.annotation.ColorInt;
import android.support.annotation.IntRange;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.ActivityOptionsCompat;
import android.support.v4.util.Pair;
import android.support.v4.view.ViewCompat;
import android.support.v7.graphics.Palette;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.animation.AccelerateInterpolator;
import android.widget.ImageView;
import android.widget.TextView;

import com.sample.andremion.musicplayer.R;
import com.sample.andremion.musicplayer.music.MusicContent;
import com.sample.andremion.musicplayer.music.MusicControl;
import com.sample.andremion.musicplayer.utils.MediaUtil;
import com.sample.andremion.musicplayer.view.RecyclerViewAdapter;

import static com.sample.andremion.musicplayer.R.id.fab;
import static com.sample.andremion.musicplayer.music.MusicContent.ITEMS;
import static com.sample.andremion.musicplayer.music.MusicControl.mService;

public class MusicActivity extends PlayerActivity {

    private View mCoverView;
    private View mTitleView;
    private View mTimeView;
    private View mDurationView;
    private View mProgressView;
    private View mFabView;
    private View pane;
    private RecyclerViewAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.content_list);

        mCoverView = findViewById(R.id.cover);
        mTitleView = findViewById(R.id.title);
        mTimeView = findViewById(R.id.time);
        mDurationView = findViewById(R.id.duration);
        mProgressView = findViewById(R.id.progress);
        mFabView = findViewById(fab);
        TextView counter = (TextView) findViewById(R.id.counter);
        pane = findViewById(R.id.pane);

        mFabView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MusicControl.playStop();
                switchFabStatus();
            }
        });

        mCoverView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                toDetailMusic();
            }
        });

        int size = ITEMS.size();
        if (size == 0)
            counter.setText("没有扫描到音乐文件");
        else
            counter.setText(size + " 首歌");
        // Set the recycler adapter
        RecyclerView recyclerView = (RecyclerView) findViewById(R.id.tracks);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        adapter = new RecyclerViewAdapter(ITEMS, this);

        adapter.setOnItemClickListener(new RecyclerViewAdapter.OnItemClickListener() {
            @Override
            public void onLongClickListener() {
                toDetailMusic();
            }

            @Override
            public void playStop() {
                switchFabStatus();
            }
        });

        recyclerView.setAdapter(adapter);

        if (mService != null) {
            switchFabStatus();
        }

    }

    private void toDetailMusic() {
        if (MusicControl.getCurrentItem() == null)
            return;
        ActivityOptionsCompat options = ActivityOptionsCompat.makeSceneTransitionAnimation(MusicActivity.this,
                new Pair<>(mCoverView, ViewCompat.getTransitionName(mCoverView)),
                new Pair<>(mTitleView, ViewCompat.getTransitionName(mTitleView)),
                new Pair<>(mTimeView, ViewCompat.getTransitionName(mTimeView)),
                new Pair<>(mDurationView, ViewCompat.getTransitionName(mDurationView)),
                new Pair<>(mProgressView, ViewCompat.getTransitionName(mProgressView)),
                new Pair<>(mFabView, ViewCompat.getTransitionName(mFabView)));
        ActivityCompat.startActivity(MusicActivity.this, new Intent(MusicActivity.this, DetailActivity.class), options.toBundle());
    }

    private void switchFabStatus() {
        FloatingActionButton fab = (FloatingActionButton) mFabView;
        if (MusicControl.isPlay())
            fab.setImageResource(R.drawable.ic_pause_vector);
        else {
            fab.setImageResource(R.drawable.ic_play_vector);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        MusicContent.MusicItem item = MusicControl.getCurrentItem();
        if (item == null)
            return;
        Bitmap artwork = MediaUtil.getArtwork(getBaseContext(), item.mId, item.mAlbumId, true, false);
        ImageView art = (ImageView) mCoverView;
        art.setImageBitmap(artwork);
        TextView title = (TextView) mTitleView;
        title.setText(item.mTitle + "-" + item.mArtist);

        MusicControl.setMusicChangeListener(musicChangeListener);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        MusicControl.removeMusicChangeListener(musicChangeListener);
        adapter.removeOnItemClickListener();
    }

    private MusicControl.OnMusicChangeListener musicChangeListener = new MusicControl.OnMusicChangeListener() {
        @Override
        public void onPlayStatusChange() {
            switchFabStatus();
        }

        @Override
        public void onChange(MusicContent.MusicItem item) {
            Bitmap artwork = MediaUtil.getArtwork(getBaseContext(), item.mId, item.mAlbumId, true, false);
            ImageView art = (ImageView) mCoverView;
            art.setImageBitmap(artwork);

            Palette.from(artwork).clearFilters().generate(new Palette.PaletteAsyncListener() {
                @Override
                public void onGenerated(Palette palette) {
                    pane.setBackgroundColor(modifyAlpha(palette.getDarkMutedColor(Color.BLACK), (int) (255 * 0.8f)));
                }
            });

            TextView title = (TextView) mTitleView;
            title.setText(item.mTitle + "-" + item.mArtist);

            art.setAlpha(0.2f);
            art.animate().alpha(1f).setInterpolator(new AccelerateInterpolator()).start();

            FloatingActionButton fab = (FloatingActionButton) mFabView;
            fab.setImageResource(R.drawable.ic_pause_vector);

            adapter.notifyDataSetChanged();

            onUpdateProgress();
        }
    };

    /**
     * Set the alpha component of {@code color} to be {@code alpha}.
     */
    public static
    @CheckResult
    @ColorInt
    int modifyAlpha(@ColorInt int color,
                    @IntRange(from = 0, to = 255) int alpha) {
        return (color & 0x00ffffff) | (alpha << 24);
    }
}
